/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package index;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Hashtable;

import map.file.FileMap;

import figures.Figure;
import figures.FigureIterator;
import file.FileGetter;
import form.ProgressListener;

public class SoundexIndexReader implements Index {

	FileGetter getter = null;
	Hashtable matches = new Hashtable();
	
	public SoundexIndexReader(FileGetter f){
		getter = f;
	}
	
	public int find(String selection, ProgressListener l) {
		matches.clear();
		System.gc();
		int num = 0;
		String soundex = NameCoder.codeWord(selection);
		DataInputStream is = new DataInputStream(getter.getResource("index"));
		String[] toSearch = null;
		try {
			while(true){
				String s = FileMap.readString(is);
				int n = is.readShort();
				String[] files= new String[n];
				for(int k=0;k<n;k++)
					files[k] = FileMap.readString(is);
				if(s.equals(soundex)){
					toSearch = files;
					break;
				}
			}
		} catch (IOException e) {
			//eof
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(l!=null)
			l.setFound(0);
		if(toSearch==null)
			return 0;
		for(int k=0;k<toSearch.length;k++){
			FileMap map = new FileMap(getter, toSearch[k]);
			FigureIterator f= map.getFigures(null);
			while(f.hasNext()){
				Figure fig = f.next();
				String[] partesNombre = NameCoder.split(fig.getName());
				for(int i=0;i<partesNombre.length;i++){
					if(partesNombre[i]==null)
						continue;
					String figSoundex = NameCoder.codeWord(partesNombre[i]);
					if(soundex.equals(figSoundex)){
						matches.put(new Integer(num++), fig);
						if(l!=null)
							l.setFound(num);
					}
				}
			}
			map = null;
			System.gc();
		}
		return num;
	}

	public Figure getFigure(int i) {
		return (Figure)matches.get(new Integer(i));
	}
}
